package com.masterclient.app.modules.cart;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.eoner.baselib.utils.notify.RxBus;
import com.eoner.baselib.utils.sp.SPUtils;
import com.eoner.baselib.utils.toast.ToastUtil;
import com.eoner.baselibrary.bean.order.ConfirmOrderData;
import com.eoner.baselibrary.utils.Utils;
import com.eoner.common.config.Config;
import com.eoner.managerlibrary.router.AroutePath;
import com.eoner.managerlibrary.user.UserDataManager;
import com.masterclient.app.BaseFragment;
import com.masterclient.app.MainActivity;
import com.masterclient.app.R;
import com.masterclient.app.base.ConfirmDialog;
import com.masterclient.app.base.ProgressLoginDialog;
import com.masterclient.app.modules.cart.adapter.ShopCartAdapter;
import com.masterclient.app.modules.cart.adapter.ShopCartAdapterListener;
import com.masterclient.app.modules.cart.beans.ProductsItemBean;
import com.masterclient.app.modules.cart.beans.ShopCartBean;
import com.masterclient.app.modules.cart.beans.ShopCartCustomItemBean;
import com.masterclient.app.modules.cart.contract.ShopCartContract;
import com.masterclient.app.modules.cart.contract.ShopCartPresenter;
import com.masterclient.app.modules.goods.newpage.activity.NewCommodityDetailActivity;
import com.masterclient.app.widget.UpgradeVipLayout;
import com.eoner.uikit.header.MyRefreshHead;
import com.gyf.immersionbar.ImmersionBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = AroutePath.SHOP_CART_FRAGMENT)
public class ShopCartFragment extends BaseFragment<ShopCartPresenter> implements ShopCartContract.View{

    public static String TAG = "ShopCartFragment";

    @BindView(R.id.rl_back)
    RelativeLayout rlBack;
    @BindView(R.id.fl_head)
    FrameLayout flHead;
    @BindView(R.id.ll_head)
    LinearLayout llHead;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_edit)
    TextView tvEdit;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.cb_check_all)
    CheckBox cbCheckAll;
    @BindView(R.id.ll_all_price)
    LinearLayout llAllPrice;
    @BindView(R.id.tv_money_flag)
    TextView tvMoneyFlag;
    @BindView(R.id.tv_sum)
    TextView tvSum;
    @BindView(R.id.tv_coin_num)
    TextView tvCoinNum;
    @BindView(R.id.tv_coin)
    TextView tvCoin;
    @BindView(R.id.ll_edit_status)
    LinearLayout llEditStatus;
    @BindView(R.id.tv_confirm)
    TextView tvConfirm;
    @BindView(R.id.rl_bottom)
    LinearLayout rlBottom;
    @BindView(R.id.promotion_price)
    TextView promotionPrice;
    @BindView(R.id.upgrade_vip_layout)
    UpgradeVipLayout upgradeVipLayout;
    @BindView(R.id.swipeLayout)
    SmartRefreshLayout swipeLayout;

    @Autowired(name = "from")
    String from;

    private ProgressLoginDialog progressLoginDialog;
    private ShopCartAdapter shopCartAdapter;
    private List<ShopCartCustomItemBean> mShopCartCustomItemBean;
    private List<ProductsItemBean> productsList = new ArrayList<>();
    private boolean isEdit = false;
    private boolean isVisible = true;
    private RxBus rxBus;
    private String meetReducePrice;
    private String buyTotal, buyNum;
    private String confirmJumpType;
    private String saleType;
    private ShopCartDoDataUtil shopCartDoDataUtil;
    private ShopCartBean shopCartBean;

    public static ShopCartFragment newInstance() {
        return new ShopCartFragment();
    }

    @Override
    protected View getRootView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.fragment_shop_cart, null);
    }

    @Override
    protected void initOnlyOnce() {
        super.initOnlyOnce();

        Utils.setDin(tvSum, mContext);
        Utils.setDin(tvCoinNum, mContext);
        ARouter.getInstance().inject(this);

        shopCartDoDataUtil = new ShopCartDoDataUtil();
        if ("activity".equals(from)) {
            rlBack.setVisibility(View.VISIBLE);
        } else {
            rlBack.setVisibility(View.GONE);
            llHead.setPadding(0, ImmersionBar.getStatusBarHeight(Objects.requireNonNull(getActivity())), 0, 0);
        }

        rxBus = RxBus.$();
        rxBus.OnEvent(rxBus.register(Config.SUBMIT_ORDER), o -> {
            mPresenter.getShopCartList(shopCartDoDataUtil.getSelectedCartIds(mShopCartCustomItemBean), progressLoginDialog);
            recyclerView.scrollToPosition(0);
            tvSum.setText(R.string.zero);
            tvConfirm.setText("结算");
            buyTotal = "0";
            buyNum = "0";
        });

        swipeLayout.setRefreshHeader(new MyRefreshHead(getActivity()));
        swipeLayout.setOnRefreshListener(refreshLayout -> mPresenter.getShopCartList(shopCartDoDataUtil.getSelectedCartIds(mShopCartCustomItemBean), progressLoginDialog));
        progressLoginDialog = new ProgressLoginDialog(Objects.requireNonNull(getActivity()));
        shopCartAdapter = new ShopCartAdapter(shopCartAdapterListener);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setAdapter(shopCartAdapter);
    }

    @Override
    public void onResume() {
        MobclickAgent.onEvent(mContext, "page_cart");
        super.onResume();
        if (!TextUtils.isEmpty(SPUtils.getInstance().getString(Config.CUSTOMERID)) && isVisible) {
            mPresenter.getShopCartList(shopCartDoDataUtil.getSelectedCartIds(mShopCartCustomItemBean), progressLoginDialog);
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        isVisible = !hidden;
        if (!TextUtils.isEmpty(SPUtils.getInstance().getString(Config.CUSTOMERID)) && isVisible) {
            mPresenter.getShopCartList(shopCartDoDataUtil.getSelectedCartIds(mShopCartCustomItemBean), progressLoginDialog);
        }
    }


    @OnClick({R.id.tv_edit, R.id.ll_check_all, R.id.tv_collect, R.id.tv_delete, R.id.tv_confirm, R.id.rl_back})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_edit:
                if (isEdit) {
                    tvEdit.setText("编辑");
                    isEdit = false;
                    llEditStatus.setVisibility(View.GONE);
                    llAllPrice.setVisibility(View.VISIBLE);
                    if (!TextUtils.isEmpty(meetReducePrice) && !"0".equals(meetReducePrice)) {
                        promotionPrice.setVisibility(View.VISIBLE);
                        promotionPrice.setText(String.format("促销减 ¥%s", meetReducePrice));
                    } else {
                        promotionPrice.setVisibility(View.GONE);
                    }
                    tvConfirm.setVisibility(View.VISIBLE);
                } else {
                    tvEdit.setText("完成");
                    isEdit = true;
                    llEditStatus.setVisibility(View.VISIBLE);
                    llAllPrice.setVisibility(View.GONE);
                    promotionPrice.setVisibility(View.GONE);
                    tvConfirm.setVisibility(View.GONE);
                }
                break;
            case R.id.ll_check_all:
                if (shopCartDoDataUtil.isCheckAll()) {
                    shopCartDoDataUtil.doCheckAll(false, mShopCartCustomItemBean, cbCheckAll, shopCartAdapter, mPresenter, progressLoginDialog);
                } else {
                    shopCartDoDataUtil.doCheckAll(true, mShopCartCustomItemBean, cbCheckAll, shopCartAdapter, mPresenter, progressLoginDialog);
                }
                break;
            case R.id.tv_collect:
                if (!TextUtils.isEmpty(shopCartDoDataUtil.getSelectedCartIds(mShopCartCustomItemBean))) {
                    mPresenter.collectShopCartList(shopCartDoDataUtil.getSelectedCartIds(mShopCartCustomItemBean), progressLoginDialog);
                } else {
                    showToast("您还没有选中宝贝哦");
                }
                break;
            case R.id.tv_delete:
                if (!TextUtils.isEmpty(shopCartDoDataUtil.getSelectedCartIds(mShopCartCustomItemBean))) {
                    ConfirmDialog dialog = new ConfirmDialog(mContext, "确认删除这些商品吗？", "取消", "确定");
                    dialog.setOnChooseListerner(new ConfirmDialog.OnChooseListerner() {
                        @Override
                        public void cancel() {
                            dialog.dismiss();
                        }

                        @Override
                        public void confirm() {
                            mPresenter.deleteShopCartList(shopCartDoDataUtil.getSelectedCartIds(mShopCartCustomItemBean), progressLoginDialog);
                            dialog.dismiss();
                        }
                    });
                    dialog.show();
                } else {
                    showToast("您还没有选中宝贝哦");
                }
                break;
            case R.id.tv_confirm:
                MobclickAgent.onEvent(mContext, "click_confirm_order");
                if (!TextUtils.isEmpty(shopCartDoDataUtil.getSelectedCartIds(mShopCartCustomItemBean))) {
                    if ("2".equals(confirmJumpType)) {
                        ShopCartCollectDialog dialog = new ShopCartCollectDialog(Objects.requireNonNull(getActivity()),
                                shopCartDoDataUtil.getConfirmPopData(shopCartBean), (products, saleType) -> {
                            this.saleType = saleType;
                            mPresenter.confirm_order(products, "1", saleType, progressLoginDialog);
                        });
                        dialog.show();
                    } else {
                        mPresenter.confirm_order(shopCartDoDataUtil.getBuyProduct(true, mShopCartCustomItemBean), "1",
                                saleType, progressLoginDialog);
                    }
                } else {
                    showToast("请至少购买一件哦");
                }
                break;
            case R.id.rl_back:
                Objects.requireNonNull(getActivity()).finish();
                break;
        }
    }

    @Override
    public void showShopCartList(ShopCartBean shopCartBean) {
        if (swipeLayout != null) {
            swipeLayout.finishRefresh();
        }
        progressLoginDialog.dismiss();
        if (upgradeVipLayout != null) {
            if (shopCartBean.data.upgradeToVip == null || TextUtils.isEmpty(shopCartBean.data.upgradeToVip.getMessage()) || Integer.valueOf(UserDataManager.getInstance().getRoleLevel()) > 0) {
                upgradeVipLayout.setVisibility(View.GONE);
            } else {
                upgradeVipLayout.setVisibility(View.VISIBLE);
                upgradeVipLayout.setData(shopCartBean.data.upgradeToVip, true, "购物车");
            }
        }

        if (shopCartBean != null && shopCartBean.data != null) {
            this.shopCartBean = shopCartBean;
        }

        if (shopCartBean.data != null && !TextUtils.isEmpty(shopCartBean.data.meetReducePrice)) {
            meetReducePrice = shopCartBean.data.meetReducePrice;
        }
        if (shopCartBean.data != null && !TextUtils.isEmpty(shopCartBean.data.confirmJumpType)) {
            confirmJumpType = shopCartBean.data.confirmJumpType;
        }
        if (shopCartBean.data != null && !TextUtils.isEmpty(shopCartBean.data.saleType)) {
            saleType = shopCartBean.data.saleType;
        }
        List<String> selectedHisCartIdList = shopCartDoDataUtil.getSelectedCartIdList(mShopCartCustomItemBean);
        mShopCartCustomItemBean = shopCartDoDataUtil.doShopCartApiDataToModel(shopCartBean, productsList, tvEdit, rlBottom);
        shopCartDoDataUtil.doShopCartSelected(selectedHisCartIdList, mShopCartCustomItemBean);
        shopCartAdapter.setData(mShopCartCustomItemBean);

        shopCartDoDataUtil.showCheckAll(mShopCartCustomItemBean, cbCheckAll, shopCartAdapter);
        showBottom(shopCartBean);
    }

    @Override
    public void showShopCartListFailed(String msg) {
        if (swipeLayout != null) {
            swipeLayout.finishRefresh(false);
        }
        progressLoginDialog.dismiss();
        ToastUtil.showToast(msg);
    }

    @Override
    public void updateShopCartList() {
        mPresenter.getShopCartList(shopCartDoDataUtil.getSelectedCartIds(mShopCartCustomItemBean), progressLoginDialog);
    }

    @Override
    public void updateShopCartListFailed(String msg) {
        progressLoginDialog.dismiss();
        ToastUtil.showToast(msg);
    }

    @Override
    public void collectShopCartList() {
        mPresenter.getShopCartList(shopCartDoDataUtil.getSelectedCartIds(mShopCartCustomItemBean), progressLoginDialog);
    }

    @Override
    public void collectShopCartListFailed(String msg) {
        progressLoginDialog.dismiss();
        ToastUtil.showToast(msg);
    }

    @Override
    public void deleteShopCartList() {
        mPresenter.getShopCartList(shopCartDoDataUtil.getSelectedCartIds(mShopCartCustomItemBean), progressLoginDialog);
    }

    @Override
    public void deleteShopCartListFailed(String msg) {
        progressLoginDialog.dismiss();
        ToastUtil.showToast(msg);
    }

    @Override
    public void confirm_order_success(ConfirmOrderData data, String buy_product) {
        progressLoginDialog.dismiss();
        ARouter.getInstance().build(AroutePath.ORDER_SUBMIT_ACTIVITY).withString("buy_type", "1").
                withString("buy_product", buy_product).
                withString("saleType", saleType).
                withSerializable("confirm_order_data", data).navigation();
    }

    @Override
    public void confirm_order_failed(String msg) {
        progressLoginDialog.dismiss();
        ToastUtil.showToast(msg);
    }

    /**
     * 展示底部View
     */
    private void showBottom(ShopCartBean shopCartBean) {
        if (!"0".equals(shopCartBean.data.cartNum)) {
            tvTitle.setText(String.format("购物车 (%s)", shopCartBean.data.cartNum));
        } else {
            tvTitle.setText("购物车");
        }
        if (!"0".equals(shopCartBean.data.confirmPrice)) {
            buyTotal = shopCartBean.data.confirmPrice;
            tvSum.setText(shopCartBean.data.confirmPrice);
        } else {
            buyTotal = "0";
            tvSum.setText(R.string.zero);
        }
        if (shopCartBean.data.meetReducePrice != null && !"0".equals(shopCartBean.data.meetReducePrice)) {
            promotionPrice.setVisibility(View.VISIBLE);
            promotionPrice.setText(String.format("促销减 ¥%s", shopCartBean.data.meetReducePrice));
        } else {
            promotionPrice.setVisibility(View.GONE);
        }
        if (!"0".equals(shopCartBean.data.confirmIntegralPrice)) {
            tvCoinNum.setText(String.format(" + %s", shopCartBean.data.confirmIntegralPrice));
            tvCoinNum.setVisibility(View.VISIBLE);
            tvCoin.setVisibility(View.VISIBLE);
            tvCoin.setText("金币");
        } else {
            tvCoinNum.setVisibility(View.GONE);
            tvCoin.setVisibility(View.GONE);
        }
        if (!"0".equals(shopCartBean.data.confirmNum)) {
            buyNum = shopCartBean.data.confirmNum;
            tvConfirm.setText(String.format("结算(%s)", shopCartBean.data.confirmNum));
        } else {
            buyNum = "0";
            tvConfirm.setText("结算");
        }
    }

    /**
     * Item相关点击事件处理
     */
    ShopCartAdapterListener shopCartAdapterListener = new ShopCartAdapterListener() {
        @Override
        public void onCheckShopAllGoods(String shopId, boolean isCheck) {
            shopCartDoDataUtil.doShopCheckStatus(shopId, isCheck, mShopCartCustomItemBean, cbCheckAll, shopCartAdapter);
            mPresenter.getShopCartList(shopCartDoDataUtil.getSelectedCartIds(mShopCartCustomItemBean), progressLoginDialog);
        }

        @Override
        public void onGoIntoShopPage(String shopId, String shopName, String isBoutique, String isSelfOperated, int position, boolean isDealer, boolean isAgent) {
//            ARouter.getInstance().build(AroutePath.STORE_ACTIVITY).withString("store_id", shopId)
//                    .withString("is_dealer", isDealer ? "1" : "0")
//                    .withString("is_agent", isAgent?"1":"0")
//                    .navigation();
        }

        @Override
        public void onCheckGoods(String shopId, String productId, boolean isCheck) {
            shopCartDoDataUtil.doGoodCheckStatus(shopId, productId, isCheck, mShopCartCustomItemBean, cbCheckAll, shopCartAdapter);
            mPresenter.getShopCartList(shopCartDoDataUtil.getSelectedCartIds(mShopCartCustomItemBean), progressLoginDialog);
        }

        @Override
        public void onGoIntoGoodDetails(String productId, int position) {
            Intent intent = new Intent(mContext, NewCommodityDetailActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("id", productId);
            intent.putExtra("source_page", "购物车");
            intent.putExtra("source_module", "加购商品");
            intent.putExtra("source_element", "");
            intent.putExtra("source_position", position + "");
            intent.putExtras(bundle);
            mContext.startActivity(intent);
        }

        @Override
        public void onGoIntoMain() {
            Intent intent = new Intent(getContext(), MainActivity.class);
            intent.putExtra("position", "0");
            startActivity(intent);
        }

        @Override
        public void onClearDisableGoods() {
            ConfirmDialog dialog = new ConfirmDialog(mContext, "确认清空这些商品吗？", "取消", "确定");
            dialog.setOnChooseListerner(new ConfirmDialog.OnChooseListerner() {
                @Override
                public void cancel() {
                    dialog.dismiss();
                }

                @Override
                public void confirm() {
                    mPresenter.deleteShopCartList(shopCartDoDataUtil.getDisableGoodsCartIds(mShopCartCustomItemBean), progressLoginDialog);
                    dialog.dismiss();
                }
            });
            dialog.show();
        }

        @Override
        public void onCollectGoods(String cartId) {
            mPresenter.collectShopCartList(cartId, progressLoginDialog);
        }

        @Override
        public void onDeleteGoods(String cartId) {
            ConfirmDialog dialog = new ConfirmDialog(mContext, "确认删除这个商品吗？", "取消", "确定");
            dialog.setOnChooseListerner(new ConfirmDialog.OnChooseListerner() {
                @Override
                public void cancel() {
                    dialog.dismiss();
                }

                @Override
                public void confirm() {
                    mPresenter.deleteShopCartList(cartId, progressLoginDialog);
                    dialog.dismiss();
                }
            });
            dialog.show();
        }

        @Override
        public void onReduceGoods(String cartId, String num) {
            mPresenter.updateShopCartList(cartId, num, progressLoginDialog);
        }

        @Override
        public void onPlusGoods(String cartId, String num) {
            mPresenter.updateShopCartList(cartId, num, progressLoginDialog);
        }
    };


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (rxBus != null) {
            rxBus.unregister(Config.SUBMIT_ORDER);
            rxBus = null;
        }
    }
}
